// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Coravel.Invocable;
using Elastic.Clients.Elasticsearch;
using MyDemo.Application.Service.Plc;
using SL.NET.Core.Service;
using WCS.Application.Entity.Warehous;
using WCS.Application.Service.Inventory;
using WCS.Application.Service.Inventory.DTO;
using static MyDemo.Application.Service.Plc.MqttService;
using static QRCoder.PayloadGenerator;

namespace WCS.Application.Service.Rcs;
/// <summary>
/// 设备动作调度
/// </summary>
/// 
/*[ApiDescriptionSettings(groups: ApplicationConst.GroupName, Order = 15)]
[AllowAnonymous]*/
public class OutboundOrderService : IInvocable
{
    // IDynamicApiController, ITransient
    //mqtt

    private readonly IServiceScopeFactory _serviceScopeFactory;

    //获取任务表信息
    private readonly SqlSugarRepository<WCSTaskManagementEntity> _wcsTaskEntity;
    private readonly InventorySFPService _inventorySFPService;

    public OutboundOrderService(
        IServiceScopeFactory serviceScopeFactory
        )
    {
        _serviceScopeFactory = serviceScopeFactory;

        using var serviceScope = _serviceScopeFactory.CreateScope();


        _wcsTaskEntity = serviceScope.ServiceProvider.GetService<SqlSugarRepository<WCSTaskManagementEntity>>();
        _inventorySFPService = serviceScope.ServiceProvider.GetService<InventorySFPService>();
    }


    public async Task Invoke()
    {
        SerilogHelper.WriteLog("OutboundOrderService", "start");

        try
        {
            // 查询第一个待执行的出库任务
            var lastTaskAction = await _wcsTaskEntity
                .AsQueryable()
                .Where(a => a.Type == TaskTypeEnum.Outbound
                            && a.Status == TaskStatusEnmu.NoStarte
                    )
                .OrderBy(it => it.TaskNumber)
                .FirstAsync();
            SerilogHelper.WriteLog("OutboundOrderService", "lastTaskAction", JsonHelper.ObjectToJson(lastTaskAction));
            if (lastTaskAction is not null)
            {
                SerilogHelper.WriteLog("OutboundOrderService", "出库分配结果：", JsonHelper.ObjectToJson(lastTaskAction));
                var outboundInfo = new TemporarilyOutbound()
                {
                    TaskNo = lastTaskAction.TaskNumber,
                    Hoistopening = lastTaskAction.HoistOpening,
                    Palcode = lastTaskAction.TrayCode,
                };
                SerilogHelper.WriteLog("OutboundOrderService", "出库分配请求：", JsonHelper.ObjectToJson(outboundInfo));
                var isSuccess = await _inventorySFPService.TemporaryOutbound(outboundInfo);
                SerilogHelper.WriteLog("OutboundOrderService", "出库分配结果：", isSuccess.ToString());
                if (isSuccess)
                {
                    lastTaskAction.Status = TaskStatusEnmu.Underay;
                    var rtInsert = await _wcsTaskEntity.AsUpdateable(lastTaskAction).ExecuteCommandAsync();
                    SerilogHelper.WriteLog("OutboundOrderService", "更新任务结果：", rtInsert.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            LogHelper.WriteErrorLog("OutboundOrderService", ex);
        }

        SerilogHelper.WriteLog("OutboundOrderService", "end");
    }


}
